package com.zakj.scservice.service;

import com.zakj.scservice.bean.Cabin;
import com.zakj.scservice.bean.FlightTicket;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.utils.HttpConstant;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * create by IntelliJ IDEA
 * User: HuangRZ
 * QQ: 917647409
 * Email: huangrz11@163.com
 * Date: 2017/11/22
 * Time: 9:22
 * Description:
 **/
public class SiChuanAirportPageProcessor implements PageProcessor {

    private List<FlightTicket> flightTickets;

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000).setCharset("utf-8");

    private String routStartPlace;
    private String routEndPlace;
    private String routStartTime;

    public SiChuanAirportPageProcessor(String routStartPlace, String routEndPlace, String routStartTime) {
        this.routStartPlace = routStartPlace;
        this.routEndPlace = routEndPlace;
        this.routStartTime = routStartTime;
    }

    @Override
    public void process(Page page) {
        List<String> cities = page.getHtml().xpath("//span[@class='city']/text()").all();
        if (cities.size() == 0) {
            //创建http请求
            Request request = new Request("http://www.sichuanair.com/3uair/ibe/common/processSearchForm.do");
            //只有POST请求才可以添加附加参数
            request.setMethod(HttpConstant.Method.POST);

            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("Search/AirlineMode", "false");
            params.put("Search/calendarCacheSearchDays", "60");
            params.put("Search/calendarSearched", "false");//必须
            params.put("dropOffLocationRequired", "false");
            params.put("Search/searchType", "F");//必须
            params.put("searchTypeValidator", "F");//必须
            params.put("xSellMode", "false");
            params.put("destinationLocationSearchBoxType", "L");
            params.put("Search/isUserPrice", "1");
            params.put("Search/calendarSearch", "false");
            params.put("Search/seatClass", "Y");
            params.put("Search/promotionCode", "");
            params.put("Search/OriginDestinationInformation/Origin/location", routStartPlace);//必须
            params.put("Search/OriginDestinationInformation/Destination/location", routEndPlace);//必须
            params.put("Search/DateInformation/departDate_display", routStartTime);
            params.put("Search/DateInformation/departDate", routStartTime);//必须   起飞日期
//            params.put("Search/DateInformation/returnDate", routStartTime);//回程   在单程中非必须
            params.put("Search/flightType", "oneway");//必须  飞行类型  oneway单程
            params.put("Search/Passengers/adults", "1");
            params.put("Search/Passengers/children", "0");

            request.setRequestBody(HttpRequestBody.form(params, "utf-8"));
            page.addTargetRequest(request);
        } else {
            //开始解析获取搜索数据的页面
            String str = page.getHtml().xpath("//div[@class='tbh-section']/div[@class='th-tr cl']/div[2]/text()").toString();
            if ("组合价".equals(str)){
                return;
            }

            List<String> list = page.getHtml().xpath("//div[@class='tbd-section']").all();
            //定义xpath匹配路径头
            String rout_info_str;
            String brandSubs_str;
            flightTickets = new ArrayList<FlightTicket>();
            for (int i = 2; i <= list.size() + 1; i++) {
                rout_info_str = "//div[@class='brand-tb']/div[" + (i) + "]/div[@class='tb-tr cl']/div[@class='tb-td tb-tt']";
                brandSubs_str = "//div[@class='brand-tb']/div[" + (i) + "]/div[@class='tb-data-detail']/div[@class='data-detail-item cl']";

                //获取航班编号
                String flightNumber = page.getHtml().xpath(rout_info_str + "/div[@class='route-info cl']/span[@class='flight-code']/text()").toString();
                //航空公司
                String airline = page.getHtml().xpath(rout_info_str + "/div[@class='route-info cl']/span[@class='air-text']/text()").toString();
                //航班客机类型
                String planeType = page.getHtml().xpath(rout_info_str + "/div[@class='route-info cl']/div[@class='plane-type']/span[@class='plane-trigger']/text()").toString();
                //航班起飞时间
                String routStartTime = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-start']/p[@class='route-time']/text()").toString();
                //航班起飞机场
                String routStartPlace = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-start']/p[@class='route-place']/text()").toString();
                //航班起飞日期
                String routStartDate = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-start']/p[@class='route-date']/text()").toString();
                //航班到达时间
                String routEndTime = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-end']/p[@class='route-time']/text()").toString();
                //航班到达机场
                String routEndPlace = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-end']/p[@class='route-place']/text()").toString();
                //航班到达日期
                String routEndDate = page.getHtml().xpath(rout_info_str + "/div[@class='route-start-end cl']/div[@class='route-end']/p[@class='route-date']/text()").toString();


                //获取舱位个数，用于循环舱位信息，封装每个舱位的信息
                List<String> brandSubSize = page.getHtml().xpath(brandSubs_str).all();

                //获取舱位信息（舱号，舱位价格，舱位名称等信息）
                //获取舱位名称
                List<String> cabinName = page.getHtml().xpath(
                        brandSubs_str + "/ul[@class='item-con-left']/li[1]/span[@class='brand-sub']/text()").all();
                //获取舱号
                List<String> cabinNumber = page.getHtml().xpath(
                        brandSubs_str + "/ul[@class='item-con-left']/li[2]/text()").all();
                //获取剩余票数
                List<String> ticketRemain = page.getHtml().xpath(
                        brandSubs_str + "/ul[@class='item-con-right']/li[@class='single-ticket-remain']/text()").all();
                //获取舱位价格
                List<String> cabinPrice = page.getHtml().xpath(
                        brandSubs_str + "/ul[@class='item-con-right']/li[@class='ticket-price']/text()").all();

                FlightTicket flightTicket;
                flightTicket = new FlightTicket(flightNumber, airline, planeType, routStartTime, routEndTime, routStartPlace,
                        routEndPlace, routStartDate, routEndDate);
                List<Cabin> cabins = new ArrayList<Cabin>();
                for (int j = 0; j < brandSubSize.size(); j++) {
                            cabins.add(new Cabin(cabinName.get(j), cabinNumber.get(j), new BigDecimal(cabinPrice.get(j).trim()),
                                    ticketRemain.get(j).trim().equals("") ? 0 :Integer.valueOf(ticketRemain.get(j).substring(2,3))));
                }
                flightTicket.setCabins(cabins);
                flightTickets.add(flightTicket);
            }
        }
//        System.out.println(page.getRawText());//打印抓取的html内容
    }

    @Override
    public Site getSite() {
        return site;
    }

    List<FlightTicket> getFlightTickets() {
        return flightTickets;
    }
}

